package com.iyunsir.user.controller;


import com.iyunsir.common.vo.Result;
import com.iyunsir.mem.entity.Mem;
import com.iyunsir.user.controller.query.UserListQuery;
import com.iyunsir.user.entity.User;
import com.iyunsir.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @ResponseBody
    @PostMapping("/login")
    public Result login(User param, @RequestParam("captcha") String captcha, HttpServletRequest request, HttpSession session) {
        // 验证码验证
        if (!CaptchaUtil.ver(captcha, request)) {

            return Result.fail("验证码错误");
        }
        User user = userService.login(param);

        if (user != null) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 参数1是请求密码,参数2是数据库中加密的值
            boolean matches = passwordEncoder.matches(param.getPassword(), user.getPassword());
            if (matches) {
                // 登录成功
                user.setPassword(null);
                session.setAttribute("userInfo", user);
                return Result.success();
            }
        }
        // 登录失败
        return Result.fail("用户名或密码错误");
    }

    @GetMapping
    public String user(){
        return "user/userList";
    }

    @GetMapping("/add/ui")
    public String toAddUI(){
        return "user/userAdd";
    }

    @ResponseBody
    @GetMapping("list")
    public Result<Object> getUserList(UserListQuery query){
        List<User> list = userService.queryUsers(query);
        Long count = userService.countUsers(query);
        return Result.success(list,count);
    }

    @PostMapping
    @ResponseBody
    public Result<Object> addUser(User user) {
        userService.saveUser(user);
        return Result.success("新用户已添加成功");

    }

    @GetMapping("/{id}")
    public String getMemById(@PathVariable("id") Integer id, Model model){
        User user = userService.queryUser(id);
        model.addAttribute("user", user);
        return "user/userEdit";
    }
    @DeleteMapping("/{ids}")
    @ResponseBody
    public Result<Object> deleteManByIds(@PathVariable("ids") String ids){
        userService.deleteUserByIds(ids);
        return Result.success("删除成功！");
    }
    @PutMapping("")
    @ResponseBody
    public Result<Object> modifyUser(User user){
        userService.saveUser(user);
        return Result.success("用户信息已成功修改!");

    }

}
